package cn.fengsweb.socket
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;

	public class SocketProxy extends EventDispatcher
	{
		private var _socket:Socket;
		
		public function SocketProxy()
		{
			_socket	= new Socket();
			initListener();
		}
		private function initListener():void
		{
			_socket.addEventListener(ProgressEvent.SOCKET_DATA, 		onSocketData);
			_socket.addEventListener(Event.CLOSE, 						onClose);
			_socket.addEventListener(Event.CONNECT, 					onConnect);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, 			onIOError);
			_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
		}
		
		//-----------------------socket event handler start-----------------------
		private function onSocketData(e:ProgressEvent):void
		{
			var bytes:ByteArray	= new ByteArray();
			_socket.readBytes(bytes);
			
			dispatchRecvEvent(bytes);
		}
		private function onClose(e:Event):void
		{
			dispatchStatusEvent(SocketProxyStatus.DISCONNECT);
		}
		private function onConnect(e:Event):void
		{
			dispatchStatusEvent(SocketProxyStatus.CONNECT);
		}
		private function onIOError(e:IOErrorEvent):void
		{
			dispatchStatusEvent(SocketProxyStatus.IO_ERROR);
		}
		private function onSecurityError(e:SecurityErrorEvent):void
		{
			dispatchStatusEvent(SocketProxyStatus.SECURITY_ERROR);
		}
		//-----------------------socket event handler end-----------------------
		
		//-----------------------event dispatch start-----------------------
		private function dispatchStatusEvent(type:uint):void
		{
			var event:SocketProxyEvent	= new SocketProxyEvent(SocketProxyEvent.STATUS);
				event.statusType		= type;
			dispatchEvent(event);
		}
		private function dispatchRecvEvent(bytes:ByteArray):void
		{
			var event:SocketProxyEvent	= new SocketProxyEvent(SocketProxyEvent.RECV);
				event.recvBytes			= bytes;
			dispatchEvent(event);
		}
		//-----------------------event dispatch end-----------------------
		
		//-----------------------public function start-----------------------
		public function connect(host:String, port:uint):void
		{
			_socket.connect(host, port);
		}
		public function disconnect():void
		{
			_socket.close();
		}
		public function send(bytes:ByteArray):Boolean
		{
			if(_socket.connected){
				_socket.writeBytes(bytes);
				_socket.flush();
				return true;
			}
			
			return false;
		}
		public function get connected():Boolean
		{
			return _socket.connected;
		}
		//-----------------------public function end-----------------------
	}
}